/**
 * Copyright (C) 2017, hapjs.org. All rights reserved.
 */

import path from 'path'
import fs from 'fs'

const moduler = {
  moduleList: [],
  moduleHash: {},
  init,
  contains
}

function init (conf) {
  // 目录中存在的模块
  const fileModuleList = parseRouterEntry(conf)
  // 开发者指定的模块
  const argvModuleList = conf.options.argvModuleList

  // 创建用于保存源代码地址
  if (!fs.existsSync(conf.dirDest)) {
    fs.mkdirSync(conf.dirDest)
  }
  // 创建用于保存rpk地址
  if (!fs.existsSync(conf.dirDist)) {
    fs.mkdirSync(conf.dirDist)
  }

  const filtered = fileModuleList.filter((module) => {
    return argvModuleList.length ? (argvModuleList.indexOf(module.name) >= 0) : true
  })

  filtered.forEach((loadModule) => {
    const moduleItem = {
      // 模块名称
      name: loadModule.name,
      // 模块路径
      path: loadModule.path,
      // 导出对象
      hash: require(loadModule.path)
    }
    moduler.moduleList.push(moduleItem)
    moduler.moduleHash[moduleItem.name] = moduleItem
  })
}

function parseRouterEntry (conf) {
  const mountedRouter = []
  const { pathToolkit } = conf.defaults

  const fileList = fs.readdirSync(pathToolkit)

  fileList.forEach((item) => {
    const curFile = path.join(pathToolkit, item)
    const stat = fs.statSync(curFile)
    const targRouterFile = path.join(curFile, 'router', 'index.js')
    if (stat.isDirectory() && fs.existsSync(targRouterFile)) {
      mountedRouter.push({
        name: path.basename(curFile),
        path: path.resolve(pathToolkit, targRouterFile)
      })
    }
  })
  return mountedRouter
}

function contains (name) {
  return !!moduler.moduleHash[name]
}

export default moduler
